<template>
  <m-container>
    <m-navbar title="历史工单" background="#fff">
      <view slot="right" @click="show = true"> {{ date || '选择日期' }} <m-icon name="fillarrow-down"></m-icon></view>
    </m-navbar>
    <m-mescroll-uni
      ref="mescrollRef"
      :down="{ auto: false }"
      :up="upConfig"
      height="calc(100vh - 55px)"
      :fixed="false"
      @init="mescrollInit"
      @up="upCallback"
      @down="downCallback"
      background="linear-gradient(to bottom, #def2fc, #f2f9fd)"
    >
      <in-work-box-item v-for="(item, index) in data" :key="index" :modal="item" :dict-map="dictMap" api="history" />
    </m-mescroll-uni>

    <u-calendar v-model="show" mode="range" @change="handleChange" />
  </m-container>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from '@vue/composition-api'
import { onLoad } from 'uni-composition-api'
import { inWorkHistory } from '@/api/modules/in-work'
import { getDicts } from '@/api/modules/dict'
import dayjs from 'dayjs'

export default defineComponent({
  setup(props) {
    let mescrollObj: any = null
    const state = reactive({
      upConfig: {
        empty: {
          use: true,
          icon: require('@/static/empty.png'),
          tip: '暂无数据',
        },
      },
      show: false,
      date: '',
      data: [] as any,
      dictMap: {} as any,
      params: {
        pageNum: 1,
        pageSize: 10,
        from: '',
        to: '',
      },
    })
    const mescrollInit = (mescroll: any) => {
      mescrollObj = mescroll
    }

    const upCallback = async (page) => {
      state.params.pageNum = page.num
      await fetchData()
      const { data, params } = state
      mescrollObj.endSuccess(data.length, data.length === params.pageSize)
    }

    const handleChange = (e) => {
      state.date = e.startDate.slice(5) + '~' + e.endDate.slice(5)
      state.params.from = e.startDate + ' 00:00:00'
      state.params.to = e.endDate + ' 23:59:59'
      mescrollObj.resetUpScroll()
    }

    const downCallback = () => {
      mescrollObj && mescrollObj.resetUpScroll()
    }

    const fetchData = async () => {
      const { rows }: any = await inWorkHistory(state.params)
      state.data = state.params.pageNum === 1 ? rows : [...state.data, ...rows]
    }

    onLoad(async () => {
      const startDate = dayjs().subtract(7, 'day').format('YYYY-MM-DD')
      const endDate = dayjs().format('YYYY-MM-DD')
      state.date = startDate.slice(5) + '~' + endDate.slice(5)
      state.params.from = startDate + ' 00:00:00'
      state.params.to = endDate + ' 23:59:59'

      downCallback()

      const { map } = await getDicts('ims_order_source_type')

      state.dictMap = {
        map,
      }
    })

    return {
      ...toRefs(state),
      mescrollInit,
      downCallback,
      upCallback,
      handleChange,
    }
  },
})
</script>
<style lang="scss"></style>
